package com.scuec.trainingmanagementsys.controller;

import com.scuec.trainingmanagementsys.entity.Teacher;
import com.scuec.trainingmanagementsys.service.TeacherService;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/teacher")
@CrossOrigin
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    // 通用成功响应方法（带数据）
    private Map<String, Object> success(Object data) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 200);
        result.put("msg", "操作成功");
        result.put("data", data);
        return result;
    }

    // 通用失败响应方法（带消息）
    private Map<String, Object> fail(String msg) {
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("code", 500);
        result.put("msg", msg);
        result.put("data", null);
        return result;
    }

    // 1. 整表查询
    @GetMapping("/all")
    public Map<String, Object> getAllTeachers() {
        List<Teacher> teachers = teacherService.getAllTeachers();
        return !teachers.isEmpty() ? success(teachers) : fail("查询失败或无数据");
    }

    // 2. 根据工号查询
    @GetMapping("/byNumber/{number}")
    public Map<String, Object> getByNumber(@PathVariable String number) {
        if (number == null || number.isEmpty()) {
            return fail("工号不能为空");
        }
        Teacher teacher = teacherService.getByNumber(number);
        return teacher != null ? success(teacher) : fail("查询失败，工号不存在");
    }

    // 3. 姓名模糊查询
    @GetMapping("/search/name")
    public Map<String, Object> searchByName(@RequestParam String name) {
        if (name == null || name.isEmpty()) {
            return fail("姓名不能为空");
        }
        List<Teacher> teachers = teacherService.searchByName(name);
        return !teachers.isEmpty() ? success(teachers) : fail("查询失败或无匹配记录");
    }

    // 4. 学院查询
    @GetMapping("/byCollege")
    public Map<String, Object> getByCollege(@RequestParam String college) {
        if (college == null || college.isEmpty()) {
            return fail("学院不能为空");
        }
        List<Teacher> teachers = teacherService.getByCollege(college);
        return !teachers.isEmpty() ? success(teachers) : fail("查询失败或无匹配记录");
    }

    // 5. 多条件查询
    @GetMapping("/search/nameAndCollege")
    public Map<String, Object> searchByNameAndCollege(
            @RequestParam String name,
            @RequestParam String college) {
        if (name == null || name.isEmpty() || college == null || college.isEmpty()) {
            return fail("姓名和学院均不能为空");
        }
        List<Teacher> teachers = teacherService.searchByNameAndCollege(name, college);
        return !teachers.isEmpty() ? success(teachers) : fail("查询失败或无匹配记录");
    }

    // 6. 删除单条记录
    @DeleteMapping("/delete/{number}")
    public Map<String, Object> deleteByNumber(@PathVariable String number) {
        if (number == null || number.isEmpty()) {
            return fail("工号不能为空");
        }
        int rows = teacherService.deleteByNumber(number);
        return rows > 0 ? success(rows) : fail("删除失败，工号不存在");
    }

    // 7. 多选删除
    @DeleteMapping("/deleteBatch")
    public Map<String, Object> deleteBatchByNumbers(@RequestBody List<String> numbers) {
        if (numbers == null || numbers.isEmpty()) {
            return fail("请选择要删除的工号");
        }
        int rows = teacherService.deleteBatchByNumbers(numbers);
        return rows > 0 ? success(rows) : fail("删除失败，无匹配记录");
    }

    // 8. 插入记录
    @PostMapping("/insert")
    public Map<String, Object> insertTeacher(@RequestBody Teacher teacher) {
        if (teacher == null
                || teacher.getTeacherNumber() == null
                || teacher.getTeacherNumber().isEmpty()) {
            return fail("工号和基础信息不能为空");
        }
        int rows = teacherService.insertTeacher(teacher);
        return rows > 0 ? success(rows) : fail("插入失败，可能工号已存在");
    }

    // 9. 修改记录
    @PutMapping("/update")
    public Map<String, Object> updateTeacher(@RequestBody Teacher teacher) {
        if (teacher == null
                || teacher.getTeacherNumber() == null
                || teacher.getTeacherNumber().isEmpty()) {
            return fail("工号和基础信息不能为空");
        }
        int rows = teacherService.updateTeacher(teacher);
        return rows > 0 ? success(rows) : fail("修改失败，工号不存在");
    }

    // 教师登录接口
    @PostMapping("/login")
    public Map<String, Object> teacherLogin(@RequestBody Map<String, String> loginInfo) {
        String number = loginInfo.get("teacherNumber");
        String password = loginInfo.get("password");
        if (number == null || number.isEmpty() || password == null || password.isEmpty()) {
            return fail("工号和密码不能为空");
        }
        Teacher teacher = teacherService.getByNumberAndPassword(number, password);
        if (teacher != null) {
            // 确保返回的教师对象包含所有必要字段
            Map<String, Object> result = new HashMap<>();
            result.put("code", 200);
            result.put("message", "登录成功");
            result.put("data", teacher); // 确保teacher对象包含teacherId
            return result;
        } else {
            return fail("登录失败，工号或密码错误");
        }
    }

    // 新增：教师注册接口
    @PostMapping("/register")
    public Map<String, Object> registerTeacher(@RequestBody Map<String, String> regInfo) {
        String number = regInfo.get("teacherNumber");
        String name = regInfo.get("teacherName");
        String password = regInfo.get("password");
        String college = regInfo.get("college");
        String email = regInfo.get("email");
        String phone = regInfo.get("phone");

        // 基础校验
        if (number == null || number.isEmpty()) {
            return fail("工号不能为空");
        }
        if (name == null || name.isEmpty()) {
            return fail("姓名不能为空");
        }
        if (password == null || password.isEmpty()) {
            return fail("密码不能为空");
        }

        // 检查工号是否已存在
        Teacher existing = teacherService.getByNumber(number);
        if (existing != null) {
            return fail("工号已存在");
        }

        // 创建教师对象
        Teacher teacher = new Teacher();
        teacher.setTeacherNumber(number);
        teacher.setTeacherName(name);
        teacher.setTeacherPassword(password);
        teacher.setCollege(college != null ? college : "");
        teacher.setEmail(email != null ? email : "");
        teacher.setPhone(phone != null ? phone : "");

        // 插入数据库
        int rows = teacherService.insertTeacher(teacher);
        return rows > 0 ? success(rows) : fail("注册失败");
    }

    // 获取教师总数
    @GetMapping("/count")
    public Map<String, Object> getTeacherCount() {
        int count = teacherService.getTeacherCount();
        return success(count);
    }

    // 在TeacherController.java中添加
    @GetMapping("/getTeacherIdByNumber/{teacherNumber}")
    public Map<String, Object> getTeacherIdByNumber(@PathVariable String teacherNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            Integer teacherId = teacherService.getTeacherIdByNumber(teacherNumber);
            if (teacherId != null) {
                result.put("success", true);
                result.put("data", teacherId);
                result.put("message", "获取教师ID成功");
            } else {
                result.put("success", false);
                result.put("message", "教师不存在");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取教师ID失败");
            e.printStackTrace();
        }
        return result;
    }
    // 获取教师个人资料
    @GetMapping("/profile/{teacherNumber}")
    public ResponseEntity<Map<String, Object>> getTeacherProfile(@PathVariable String teacherNumber) {
        Map<String, Object> result = new HashMap<>();
        try {
            Teacher teacher = teacherService.getTeacherProfile(teacherNumber);
            if (teacher != null) {
                result.put("message", "获取教师个人资料成功");
                result.put("data", teacher);
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "未找到该教师资料");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "获取教师个人资料失败: " + e.getMessage());
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/update/{teacherNumber}")
    public ResponseEntity<Map<String, Object>> updateTeacher(@PathVariable String teacherNumber, @RequestBody Map<String, Object> teacherData) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 从路径变量中获取教师编号
            if (teacherNumber == null || teacherNumber.isEmpty()) {
                result.put("message", "教师编号不能为空");
                return new ResponseEntity<>(result, HttpStatus.BAD_REQUEST);
            }

            // 先查询原教师信息，用于保留未更新的密码
            Teacher originalTeacher = teacherService.getByNumber(teacherNumber);
            if (originalTeacher == null) {
                result.put("message", "未找到对应编号的教师");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }

            // 创建Teacher对象并设置更新字段
            Teacher teacher = new Teacher();
            teacher.setTeacherNumber(teacherNumber);

            // 只更新请求中提供的字段，未提供的保留原值
            if (teacherData.containsKey("teacherName")) {
                teacher.setTeacherName((String) teacherData.get("teacherName"));
            } else {
                teacher.setTeacherName(originalTeacher.getTeacherName());
            }

            if (teacherData.containsKey("college")) {
                teacher.setCollege((String) teacherData.get("college"));
            } else {
                teacher.setCollege(originalTeacher.getCollege());
            }

            if (teacherData.containsKey("email")) {
                teacher.setEmail((String) teacherData.get("email"));
            } else {
                teacher.setEmail(originalTeacher.getEmail());
            }

            if (teacherData.containsKey("phone")) {
                teacher.setPhone((String) teacherData.get("phone"));
            } else {
                teacher.setPhone(originalTeacher.getPhone());
            }

            // 处理密码更新：若请求中提供了密码则更新，否则保留原密码
            if (teacherData.containsKey("teacherPassword")) {
                String password = (String) teacherData.get("teacherPassword");
                if (password != null && !password.isEmpty()) {
                    teacher.setTeacherPassword(password);
                } else {
                    // 密码为空字符串时也保留原密码
                    teacher.setTeacherPassword(originalTeacher.getTeacherPassword());
                }
            } else {
                // 未提供密码时保留原密码
                teacher.setTeacherPassword(originalTeacher.getTeacherPassword());
            }

            int rowsAffected = teacherService.updateTeacher(teacher);
            if (rowsAffected > 0) {
                result.put("message", "修改教师信息成功");
                return new ResponseEntity<>(result, HttpStatus.OK);
            } else {
                result.put("message", "修改教师信息失败，未找到对应编号的教师");
                return new ResponseEntity<>(result, HttpStatus.NOT_FOUND);
            }
        } catch (Exception e) {
            result.put("message", "修改教师信息失败: " + e.getMessage());
            e.printStackTrace();
            return new ResponseEntity<>(result, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

}
